package com.example.firstapp.storeData

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.firstapp.R
import com.example.firstapp.databinding.ActivityStoreData2rememberpassBinding

class storeData2rememberPass : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_store_data2rememberpass)

        val binding = ActivityStoreData2rememberpassBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val prefs = getPreferences(Context.MODE_PRIVATE)
        val isRemember = prefs.getBoolean("remember_password", false)
        if (isRemember) {
            // 将账号和密码都设置到文本框中
            val account = prefs.getString("username", "")
            val password = prefs.getString("password", "")
            binding.username.setText(account)
            binding.password.setText(password)
            binding.rememberPass.isChecked = true  //初始化勾选状态
        }
        binding.login.setOnClickListener {
            val username = binding.username.text.toString()
            val password = binding.password.text.toString()
            // 如果账号是admin且密码是123456，就认为登录成功
            if (username == "admin" && password == "123456") {
                val editor = prefs.edit()
                println(11111)
                println(isRemember)
                if (binding.rememberPass.isChecked) { // 检查复选框是否被选中
                    editor.putBoolean("remember_password", true)
                    editor.putString("username", username)
                    editor.putString("password", password)
                    println(2222)
                    Toast.makeText(this, "登录成功",
                        Toast.LENGTH_SHORT).show()
                } else {
                    editor.clear()
                }
                editor.apply()
                val intent = Intent(this, StoreDataActivity::class.java)
                startActivity(intent)
                finish()
            } else {
                Toast.makeText(this, "account or password is invalid",
                    Toast.LENGTH_SHORT).show()
            }
        }

    }
    private fun save(input:String){
        val editor = getSharedPreferences("data2", Context.MODE_PRIVATE).edit()
        editor.putString("input",input)
        editor.apply()  // 提交
    }
    private fun show():String{
        val prefs = getSharedPreferences("data2", Context.MODE_PRIVATE)
        val output = prefs.getString("input", "")
        return output.toString()
    }
}